/*
 * @Author: DUST
 * @Date: 2023-05-26 16:57:13
 * @LastEditors: DUST
 * @LastEditTime: 2023-05-29 11:09:01
 * @FilePath: \koa-node-ts\app\middleware\authMiddleqare.ts
 * @Description: 
 * undefined
 */

import { Context, Next } from "koa";
import { verify } from "../../utils/auth";


function AuthMiddleware (ctx: Context, next: Next) {
  let token = ctx.header["authorization"];

  if(token !== undefined && token !== "" && token.split(" ")[0] == "Bearer") {
    token = token.split(" ")[1];
    const { error } = verify(token);
    
    if(error !== null) {
      ctx.body = {
        msg:  error.message,
        code: 401,
        data: null
      }
      return ;
      
    } else {
      return next();
    }
    
  }
  ctx.body = {
    msg: "访问无权限",
    code: 401,
    data: null
  }
  return ;
}

export default AuthMiddleware;